import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Observable } from 'rxjs'
import { Reflector } from '@nestjs/core'
import { ROLES_KEY } from '../constant'
import { Role } from '../role.enum'
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(
    context: ExecutionContext
  ): boolean | Promise<boolean> | Observable<boolean> {
    // 通过反射拿到传入的数据
    const requiredRoles = this.reflector.getAllAndOverride<Role[] | boolean>(
      ROLES_KEY,
      [context.getHandler(), context.getClass()]
    )
    if (!requiredRoles) {
      return true
    } else if (requiredRoles === true) {
      return true
    }
    // TODO: 获取用户身份，判断是否通过
    return true
  }
}
